import json
import re

from django import http
from django.contrib.auth import authenticate, logout
from django.core.mail import send_mail
from django.shortcuts import render, redirect

# Create your views here.
from django.urls import reverse
from django.views import View
from django_redis import get_redis_connection
from django.contrib.auth import login
from django.contrib.auth.mixins import LoginRequiredMixin

from apps.carts.utils import merge_cart_cookie_to_redis
from apps.goods.models import SKU
from apps.users.models import User, Address
import logging

from apps.users.utils import active_email_url, check_email_active_token
from celery_tasks.email.tasks import send_active_email
from meiduomall import settings
from utils.response_code import RETCODE
from utils.views import LoginRequiredJSONMixin

logger = logging.getLogger('django')

"""
1、用户名检测重复(这个要开发一个视图)
        用户名长度5-20个的要求
2、密码 有长度限制8-20，要求为字母、数字、下划线
3、确认密码和密码一致
4、手机号 首先手机号得是个手机号，
        其次不能是已经注册过的手机号
5、图片验证码 一个后端功能
        图片验证码是为了防止计算机攻击发送短信的功能
6、短信发送
7、必须同意用户使用协议才可以注册
8、注册按钮也是个功能

必须和后端交互的是：
    1、用户名/手机号是否重复
    2、图片验证码
    3、短信
    4、注册
"""


# 注册视图
class RegisterView(View):

    def get(self, requset):
        return render(requset, 'register.html')

    def post(self, request):
        """
        1、接收前端提交的用户名、密码、手机号
        2、验证前端来的数据
            2.1、验证必传的数据是否有值
            2.2、判断用户是否符合规则
            2.3、判断密码是否符合规则
            2.4、判断确认密码和密码是否一致
            2.5、判断手机号是否符合规则
        3、数据入库
        4、返回响应
        """
        # 1、接收前端提交的用户名、密码、手机号
        data = request.POST
        username = data.get('username')
        password = data.get('password')
        password2 = data.get('password2')
        mobile = data.get('mobile')
        allow = data.get('allow')

        # 2.1、验证必传的数据是否有值
        # all()里面必须有值，只要有一个为None,则为False
        if not all([username, password, password2, mobile]):
            return http.HttpResponseBadRequest('参数有问题')
        # 2.2、判断用户是否符合规则
        if not re.match(r'[0-9a-zA-Z_]{5,20}', username):
            return http.HttpResponseBadRequest('用户名不合法')
        # 2.3、判断密码是否符合规则
        if not re.match(r'[0-9a-zA-Z_]{8,20}', password):
            return http.HttpResponseBadRequest('密码不合法')
        # 2.4、判断确认密码和密码是否一致
        if password != password2:
            return http.HttpResponseBadRequest('密码不一致')
        # 2.5、判断手机号是否符合规则
        if not re.match(r'1[345789]\d{9}', mobile):
            return http.HttpResponseBadRequest('手机号不一致')
        # 2.6、判断同意协议是否勾选
        if allow == 'false':
            return http.HttpResponseBadRequest('请勾选同意协议')
        # 接收短信验证码
        sms_code_client = request.POST.get('sms_code')
        # 比对验证码数据
        redis_conn = get_redis_connection('code')
        sms_code_server = redis_conn.get('sms_%s' % mobile)
        if sms_code_server is None:
            return render(request, 'register.html', {'sms_code_errmsg': '无效的短信验证码'})
        if sms_code_client != sms_code_server.decode():
            return render(request, 'register.html', {'sms_code_errmsg': '输入短信验证码有误'})

        # 3、数据入库
        # User.object.create    直接入库，没毛病，只不过密码是明文的
        try:
            user = User.objects.create_user(username=username, password=password, mobile=mobile)
        except Exception as e:
            logger.error(e)
            return render(request, 'register.html', context={'error_message': '数据库异常'})
            return http.HttpResponseBadRequest('数据库异常')

        # 4、返回相应，挑战到首页
        # 注册之后默认是登录的
        # 保持登录状态，用session
        # 系统帮我们实现了这个

        login(request, user)
        return redirect(reverse('contents:index'))
        # return http.HttpResponse('注册成功')


# 验证用户名是否重复
class UsernameCountView(View):
    def get(self, requset, username):
        # 1、接收用户名
        # 在参数中传过来了
        # 2、查询数据库
        try:
            count = User.objects.filter(username=username).count()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 400, 'errmsg': '数据库异常'})

        # 返回相应
        return http.JsonResponse({'code': 0, 'count': count})


# 验证手机号是否重复
class MobileCountView(View):
    def get(self, requset, mobile):
        # 1、接收用户名
        # 在参数中传过来了
        # 2、查询数据库
        try:
            count = User.objects.filter(mobile=mobile).count()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 400, 'errmsg': '数据库异常'})

        # 返回相应
        return http.JsonResponse({'code': 0, 'count': count})


# 登录视图
class LoginView(View):
    def get(self, request):
        return render(request, 'login.html')

    def post(self, request):
        """
        实现登录逻辑
        :param request: 请求对象
        :return: 登录结果
        """
        # 接受参数
        username = request.POST.get('username')
        password = request.POST.get('password')
        remembered = request.POST.get('remembered')

        # 校验参数
        # 判断参数是否齐全
        if not all([username, password]):
            return http.HttpResponseBadRequest('缺少必传参数')

        # 判断用户名是否是5-20个字符
        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
            return http.HttpResponseBadRequest('请输入正确的用户名或手机号')

        # 判断密码是否是8-20个数字
        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return http.HttpResponseBadRequest('密码最少8位，最长20位')

        # 认证登录用户
        user = authenticate(username=username, password=password)

        # is_authenticated 是否是认证用户
        # 登录用户返回 true
        # 未登录用户返回 false
        if user is not None:
            # 6.如果验证成功则登陆,状态保持
            # 登陆成功
            login(request, user)

            if remembered == 'on':
                # 记住登陆
                # request.session.set_expiry(seconds)
                request.session.set_expiry(30 * 24 * 3600)
            else:
                # 不记住
                request.session.set_expiry(0)

            # 如果有next参数，则说明用户是点击了用户中心，却没有登录导致的。我们要跳转到用户中心
            # 如果没有next参数，则跳转到首页
            next = request.GET.get('next')
            if next:
                # 跳转到用户中心
                response = redirect(next)
            else:
                # 跳转到首页
                response = redirect(reverse('contents:index'))

            # 设置cookie
            # response.set_cookie(key,value,max_age)
            response.set_cookie('username', user.username, max_age=14 * 24 * 3600)

            # 合并购物车数， cookie-->redis
            merge_cart_cookie_to_redis(request, user, response)

            return response
        else:
            # 登陆失败
            # 7.如果验证不成功则提示 用户名或密码错误
            return render(request, 'login.html', context={'account_errmsg': '用户名或密码错误'})


"""
用户点击退出，就把登录的信息删除
执行 request.session.flush()
"""


class LoginoutView(View):
    def get(self, request):
        # request.session.flush()
        # 系统也给我们提供了退出的方法
        logout(request)
        # 退出之后，要跳转到指定页面
        # 这里，我们还跳转到首页
        # 我们要额外删除cookie中的name，因为我们首页的信息展示是读取的cookie
        response = redirect(reverse('contents:index'))
        response.delete_cookie('username')
        return response


"""
用户中心
    只有登录的用户才显示
"""


class UserCenterInfoView(LoginRequiredMixin, View):
    def get(self, request):
        # requset.user就是登录用户的信息
        context = {
            'username': request.user.username,
            'email': request.user.email,
            'mobile': request.user.mobile,
            'email_active': request.user.email_active,
        }
        return render(request, 'user_center_info.html', context=context)


"""
1、接收数据
2、验证数据
3、保存数据（更新指定用户的邮箱信息）
4、发送激活邮件
    4.1、激活邮件的内容
    4.2、能够发送激活邮件
5、返回相应

GET     ：一般是获取书籍
POST    ：一般是注册（新增）数据

PUT     ：一般是修改数据（提交的数据在请求体里面）
DELETE  ：一般是删除数据

我们这里用PUT
"""
"""
使用情景：
    当我们没有登录的时候，而我们又去请求了ajax数据，按理说应该返回json数据。
    但是却返回的是登录界面
解决方法：
    重写LoginRequireMinxin方法
"""


class EmailView(LoginRequiredJSONMixin, View):
    def put(self, request):
        # 1、接收数据
        data = json.loads(request.body.decode())  # 因为put数据在请求体里。还是二进制数据，要decode
        email = data.get('email')
        # 2、验证数据
        if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
            return http.JsonResponse({'code': RETCODE.PARAMERR, 'errmsg': '参数错误'})
        # 3、保存数据（更新指定用户的邮箱信息）
        try:
            request.user.email = email
            request.user.save()
        except Exception as e:
            return http.JsonResponse({'code': RETCODE.DBERR, 'errmsg': '数据保存失败'})
        # # 4、发送激活邮件
        # #     4.1、激活邮件的内容
        # # subject：主题
        # subject = '美多商城激活邮件'
        # # message：邮件内容
        # message = '内容测试'
        # # from_email：谁发送的
        # from_email = settings.EMAIL_FROM
        # # recipient_list：收件人列表
        # recipient_list = [email]
        # # 有格式的内容
        # html_message = '<h1>h1</h1><br><h2>h2</h2><br>'
        # #     4.2、能够发送激活邮件
        # send_mail(
        #     subject=subject,
        #     message=message,
        #     from_email=from_email,
        #     recipient_list=recipient_list,
        #     html_message=html_message,
        # )

        verify_url = active_email_url(email, request.user.id)
        # 发送激活邮件
        send_active_email(email, verify_url)
        # 5、返回相应
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'ok'})


"""
用户点击激活邮件里面的url之后，进行装填激活。在数据库里有个email_active是激活状态
"""


class EmailActiveView(View):
    def get(self, request):
        # 获取token
        token = request.GET.get('token')
        if token is None:
            return http.HttpResponseBadRequest('缺少参数')

        # 解密数据,这里返回的是用户
        user = check_email_active_token(token)
        if user is None:
            return http.HttpResponseBadRequest('没有此用户')

        # 修改用户信息，把email_active改为True，让邮件激活
        user.email_active = True
        user.save()
        return redirect(reverse('users:center'))


"""
地址管理
"""
"""
    增：POST
    删：DELETE
    改：PUT
    查：GET
    

增加收货地址
1、接收数据
    收件人、地址、省市区、邮箱、手机、固定电话
2、验证数据
    验证数据格式
3、数据入库
4、返回响应
    因为是用ajax请求，所有要返回json数据


"""


class AddressView(LoginRequiredJSONMixin, View):
    # 用户中心界面
    def get(self, request):
        # 1、查询信息
        addresses = Address.objects.filter(user=request.user, is_deleted=False)
        # 2、将对象列表转化为字典列表
        addresses_list = []
        for address in addresses:
            addresses_list.append({
                "id": address.id,
                "title": address.title,
                "receiver": address.receiver,
                "province": address.province.name,
                "province_id": address.province_id,
                "city": address.city.name,
                "city_id": address.city_id,
                "district": address.district.name,
                "district_id": address.district_id,
                "place": address.place,
                "mobile": address.mobile,
                "tel": address.tel,
                "email": address.email
            })
        context = {
            'default_address_id': request.user.default_address_id,
            'addresses': addresses_list,
        }
        return render(request, 'user_center_site.html', context=context)

    def post(self, request):
        # 一个人最多20个地址
        # 先判断当前用户的地址有多少个
        # Address.objects.filter(user=request.user).count()>20
        count = request.user.addresses.all().count()
        if count >= 20:
            return http.JsonResponse({'code': RETCODE.THROTTLINGERR, 'errmsg': '地址超过上限'})
        # 1、接收数据
        json_dict = json.loads(request.body.decode())
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')

        #     收件人、地址、省市区、邮箱、手机、固定电话
        # 2、验证数据
        #     验证数据格式
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return http.HttpResponseBadRequest('缺少必传参数')
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.HttpResponseBadRequest('参数mobile有误')
        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return http.HttpResponseBadRequest('参数tel有误')
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return http.HttpResponseBadRequest('参数email有误')
        # 3、数据入库
        try:
            address = Address.objects.create(
                user=request.user,
                title=receiver,
                receiver=receiver,
                province_id=province_id,
                city_id=city_id,
                district_id=district_id,
                place=place,
                mobile=mobile,
                tel=tel,
                email=email,
            )
        except Exception as e:
            logger.error(e)

        # 如果当前用户没有默认地址，就添加个默认地址
        if not request.user.default_address:
            request.user.default_address = address
            request.user.save()
        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }
        # 4、返回响应
        #     因为是用ajax请求，所有要返回json数据
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'ok', 'address': address_dict})


# 更新收货地址视图
# 删除收货地址视图
class AddressUpdateView(LoginRequiredJSONMixin, View):
    def put(self, request, address_id):
        # 1、接收前端提交的修改数据
        json_dict = json.loads(request.body.decode())
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')

        # 校验参数
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return http.HttpResponseBadRequest('缺少必传参数')
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.HttpResponseBadRequest('参数mobile有误')
        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return http.HttpResponseBadRequest('参数tel有误')
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return http.HttpResponseBadRequest('参数email有误')

        # 3、获取修改哪条数据（id）
        # 4、根据id查询数据
        # 5、更新（修改）数据
        # 判断地址是否存在,并更新地址信息
        try:
            Address.objects.filter(id=address_id).update(
                user=request.user,
                title=receiver,
                receiver=receiver,
                province_id=province_id,
                city_id=city_id,
                district_id=district_id,
                place=place,
                mobile=mobile,
                tel=tel,
                email=email
            )
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': RETCODE.DBERR, 'errmsg': '更新地址失败'})
        # 6、返回响应
        address = Address.objects.get(id=address_id)
        address = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '更新地址成功', 'address': address})

    def delete(self, request, address_id):
        # 1、获取删除哪条数据（address_id)
        # 2、查询数据库
        try:
            address = Address.objects.get(id=address_id)
        except Address.DoesNotExist:
            return http.JsonResponse({'code': RETCODE.NODATAERR, 'errmsg': '暂无此数据'})
        # 3、删除数据
        # address.delete()  物理删除，逻辑删除就好
        try:
            address.is_deleted = True  # 逻辑删除
            address.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': RETCODE.DBERR, 'errmsg': '删除失败'})
        # 4、返回响应
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '删除成功'})


# 设置默认地址
class DefaultAddressView(LoginRequiredJSONMixin, View):
    """设置默认地址"""

    def put(self, request, address_id):
        """设置默认地址"""
        try:
            # 接收参数,查询地址
            address = Address.objects.get(id=address_id)

            # 设置地址为默认地址
            request.user.default_address = address
            request.user.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': RETCODE.DBERR, 'errmsg': '设置默认地址失败'})

        # 响应设置默认地址结果
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '设置默认地址成功'})


# 设置地址标题
class UpdateTitleAddressView(LoginRequiredJSONMixin, View):
    """设置地址标题"""

    def put(self, request, address_id):
        """设置地址标题"""
        # 接收参数：地址标题
        json_dict = json.loads(request.body.decode())
        title = json_dict.get('title')

        try:
            # 查询地址
            address = Address.objects.get(id=address_id)

            # 设置新的地址标题
            address.title = title
            address.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': RETCODE.DBERR, 'errmsg': '设置地址标题失败'})

        # 4.响应删除地址结果
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '设置地址标题成功'})


# 展示修改密码界面和修改密码
class ChangePasswordView(LoginRequiredMixin, View):
    """修改密码"""

    def get(self, request):
        """展示修改密码界面"""
        return render(request, 'user_center_pass.html')

    def post(self, request):
        """实现修改密码逻辑"""
        # 1.接收参数
        old_password = request.POST.get('old_password')
        new_password = request.POST.get('new_password')
        new_password2 = request.POST.get('new_password2')
        # 2.验证参数
        if not all([old_password, new_password, new_password2]):
            return http.HttpResponseForbidden('缺少必传参数')
        if not re.match(r'^[0-9A-Za-z]{8,20}$', new_password):
            return http.HttpResponseBadRequest('密码最少8位，最长20位')
        if new_password != new_password2:
            return http.HttpResponseBadRequest('两次输入的密码不一致')

        # 3.检验旧密码是否正确
        if not request.user.check_password(old_password):
            return render(request, 'user_center_pass.html', {'origin_password_errmsg': '原始密码错误'})
        # 4.更新新密码
        try:
            request.user.set_password(new_password)
            request.user.save()
        except Exception as e:
            logger.error(e)
            return render(request, 'user_center_pass.html', {'change_password_errmsg': '修改密码失败'})
        # 5.退出登陆,删除登陆信息
        logout(request)
        # 6.跳转到登陆页面
        response = redirect(reverse('users:login'))

        response.delete_cookie('username')

        return response


class AddUserHistroyView(LoginRequiredJSONMixin, View):
    """
    添加用户浏览记录
    和获取用户历史记录
    """

    def post(self, request):
        # 1、接受数据    用户信息、商品ID
        user = request.user
        data = json.loads(request.body.decode())
        sku_id = data.get('sku_id')
        # 2、验证数据
        try:
            SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return http.JsonResponse({'code': RETCODE.NODATAERR, 'errmsg': '暂无此商品'})
        # 3、保存数据（Redis中）
        # 3.1、链接Redis
        redis_conn = get_redis_connection('history')
        # 3.2、删除有可能存在的这个商品ID(不然会出现5个历史记录是同一个商品)
        redis_conn.lrem('history_%s' % user.id, 0, sku_id)
        # 3.3、添加商品ID
        redis_conn.lpush('history_%s' % user.id, sku_id)
        # 3.4、只保存5条历史记录
        redis_conn.ltrim('history_%s' % user.id, 0, 4)
        # 4、返回相应
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'ok'})

    def get(self, request):
        # 1、根据用户ID，获取Redis中的指定数据
        user = request.user
        redis_conn = get_redis_connection('history')
        # 2、根据ID查询商品详细信息
        ids = redis_conn.lrange('history_%s' % user.id, 0, 4)
        # 3、对象转换为字典
        sku_list = []
        for id in ids:
            # pk就是主键primary key
            sku = SKU.objects.get(pk=id)
            sku_list.append({
                'id': sku.id,
                'name': sku.name,
                'default_image_url': sku.default_image.url,
                'price': sku.price
            })
        # 4、返回相应
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'ok', 'skus': sku_list})
